package com.wx.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wx.entity.Admin;
import com.wx.service.AdminService;
import com.wx.utils.KLKJCons;
import com.wx.utils.KLKJUtil;
import com.wx.utils.pay.MD5;


@Controller
@RequestMapping("")
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    
	@Autowired
	private AdminService adminInfoService;
	
	@RequestMapping("/")
    public String main2(Model model){
		return "/login";
    }
	
	@RequestMapping("/index")
    public String index(Model model){
		try {
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/login";
	}
	
	/*@RequestMapping("/error")
	public String error(Model model){
		return "/commons/error";
	}*/
	
    /**
	 * <p>登录页面</p>
	 * 
	 * @return
	 */
	@RequestMapping("/login")
	public String login() {
		logger.info("账号登录");
		try {
			//return "redirect:admin/index";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "login";
	}
	

	@RequestMapping(value="logon", method=RequestMethod.GET)
	public String logon() {
		return "redirect:login";
	}
	
	/**
	 * 账号登录请求处理
	 * 
	 * @return
	 */
	@RequestMapping(value="logon", method=RequestMethod.POST)
	public String logon(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value="username" ,required=false) String username,
    		@RequestParam(value="password" ,required=false) String password,
    		Model model) {
		logger.info("账号登录");
		try {
			password = MD5.MD5Encode(password);
			Admin info = adminInfoService.getAdminByName(username, password);
			if(KLKJUtil.isEmpty(info)){
				model.addAttribute("msg", "账号不存在");
				return "login";
			}
			if(!info.getAdminPassword().equals(password)){
				model.addAttribute("username", username);
				model.addAttribute("msg", "密码不正确");
				return "login";
			}
			request.getSession().setAttribute(KLKJCons.ACCOUNT_SESSION,info);
		} catch (Exception e) {
			logger.error("账号登录程序异常", e);
		}
		return "redirect:admin/productManage";
	}
	
	/**
	 * 
	 * <p>账号登出操作处理</p>
	 * 
	 * @return
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request) {
		try {
			request.getSession().removeAttribute(KLKJCons.ACCOUNT_SESSION);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return "redirect:login";
	}
}
